package com.rfid.afd.presenter;

import android.os.Handler;
import android.text.TextUtils;

import com.rfid.afd.activity.listener.ModelListener;
import com.rfid.afd.activity.view.IShangjiaView;
import com.rfid.afd.activity.view.IView;
import com.rfid.afd.model.ShangjiaModel;
import com.rfid.db.bean.Operation;
import com.rfid.db.bean.Rfid;
import com.rfid.util.DBManager;
import com.rfid.util.LogUtils;
import com.rfid.util.RfidManager;
import com.rfid.util.UserManager;
import com.rfid.util.Util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ShangjiaPresenter extends BasePresenter<IShangjiaView> implements ModelListener {

    protected ExecutorService mExecutor;
    protected Handler mHandler;
    private ShangjiaModel mModel;
    private List<Operation> mOperations;

    public ShangjiaPresenter() {
        mHandler = new Handler();
        mExecutor = Executors.newSingleThreadExecutor();
        mModel = new ShangjiaModel();
        mModel.setRfidListener(this);
        mOperations = new ArrayList<>();
    }

    @Override
    public void detach() {
        super.detach();
        mModel.setRfidListener(null);
    }

    @Override
    public void onRfid(String uid) {
        LogUtils.v("ShangjiaPresenter uid = " + uid);
        if(TextUtils.isEmpty(uid)) {
            return;
        }
        if(mIview == null) {
            return;
        }
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                Rfid rfid = mModel.getRfidByUid(uid);
                if(rfid == null) {
                    return;
                }
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mIview.onRfidScaned(rfid);
                    }
                });
            }
        });
    }

    public void addShangjiaLog(Rfid rfid) {
        Operation operation = new Operation();
        operation.setOperation(Operation.OPERATE_SHANGJIA);
        operation.setRfid(rfid.getId());
        operation.setDate(Util.getDateTime());
        operation.setUser(UserManager.getInstance().getLoginUser().getName());
        operation.setStatus(rfid.getFlag() == Rfid.FLAG_ERR_SHELF ? 1 : 0);
        if(!mOperations.contains(operation)) {
            mOperations.add(operation);
        }
    }

    public void updateOperation() {
        for(Operation operation : mOperations) {
            DBManager.insertOperation(operation);
        }
        mOperations.clear();
    }

    public void startScanRfid() {
        mModel.startScan();
    }

    public void stopScanRfid() {
        mModel.stopScan();
    }

    @Override
    public void onRfid(String epc, String barcode) {
    }
}
